
local skynet = require "skynet"
local utils = require "utils"

local CMD = {}

function CMD.execorder (order)
    local ret = skynet.call("mysqlserver", "lua", "executiveOrder", order)
    return ret
end


function CMD.insertdata (_dbname,data)
    skynet.send("mysqlserver", "lua", "insert", _dbname,data)
end


function CMD.updatedata (_dbname,data,uid)
    skynet.send("mysqlserver", "lua", "update", _dbname,data,"uid="..uid)
end


function CMD.removedata (_dbname,uid)
    skynet.send("mysqlserver", "lua", "delete", _dbname,"uid="..uid)
end


function CMD.setdata (_dbname,data,uid)
    skynet.send("mysqlserver", "lua", "setData", _dbname,data,uid)
end

function CMD.loaddata (_dbname,uid)
    local ret = skynet.call("mysqlserver", "lua", "getData", _dbname,"*","uid="..uid)
    return ret
end


function CMD.loaddataforkey (_dbname,keys,order)
    local ret = skynet.call("mysqlserver", "lua", "getData", _dbname,keys,order)
    return ret
end


function CMD.updatedataforkey (_dbname,data,keys)
    local ret = skynet.call("mysqlserver", "lua", "update", _dbname,data,keys)
    return ret
end


function CMD.loaddatafornum (_dbname, start,num,readdb,keyorder )
    -- print ("start "..start)
    local order = "uid>"..start
    if keyorder ~= nil then
        order = order .. " and ".. keyorder
    end
    order = order .. " limit "..num

    local ret = skynet.call("mysqlserver", "lua", "getData", _dbname,"*",order)
    readdb(ret)
    -- utils.dumpprint(ret)
    if #ret > 0 then
        local lastid = ret[#ret].uid
        if lastid - start >= num then
            loaddata(_dbname, lastid,num,readdb,keyorder)
        end
    end
end


function CMD.loaddataforids(_dbname,ids,readdb)

    local tempuid = {}
    local tempnum = 0
    local tempstring = "("

    for k,v in pairs(ids) do
        if tempnum > 0 then
            tempstring = tempstring .. ","
        end
        tempstring = tempstring .. v.uid
        tempnum = tempnum + 1
        if tempnum >= 1000 then
            tempstring = tempstring .. ")"
            tempuid[#tempuid + 1] = tempstring
            tempnum = 0
            tempstring = "("
        end
    end

    for i,v in ipairs(tempuid) do
        local ret = skynet.call("mysqlserver", "lua", "getData", _dbname,"*","uid in "..v)
        readdb(ret)
    end
end

return CMD